<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pagedocument extends CI_Model {
    public function __construct() {
    	parent::__construct();
    	$this->load->model('page');
    }
	    
    public function getPageDocuments($options = array()) {   
    	$options = _default(array('sortDirection' => 'asc'), $options);
    	$queryFields = array('dp_page');
        $this->db->select('acs_documents.*');
        $this->db->from('acs_documents');
        $this->db->join('acs_documents_pages', 'doc_id = dp_document');
    	foreach ($queryFields as $field) {
    		if (isset($options[$field]))
    			$this->db->where($field, $options[$field]);
    	}
    	
    	if (isset($options['limit']) && isset($options['offset']))
    		$this->db->limit($options['limit'], $options['offset']);
    	else if (isset($options['limit']))
    		$this->db->limit($options['limit]']);
    	
    	if (isset($options['sortBy']))
    		$this->db->order_by($options['sortBy'],
    		                    $options['sortDirection']);
    	$query = $this->db->get();
    	if ($query->num_rows() == 0)
    		return FALSE;
    	return $query->result_array();     
    }
    
    public function countPageDocuments($options = array()) {   
    	$queryFields = array('dp_page');
        $this->db->select('acs_documents.*');
        $this->db->from('acs_documents');
        $this->db->join('acs_documents_pages', 'doc_id = dp_document');
    	foreach ($queryFields as $field) {
    		if (isset($options[$field]))
    			$this->db->where($field, $options[$field]);
    	}
    	
    	if (isset($options['limit']) && isset($options['offset']))
    		$this->db->limit($options['limit]'], $options['offset']);
    	else if (isset($options['limit']))
    		$this->db->limit($options['limit]']);
    	
    	return $this->db->count_all_results();
    }
    
    public function moveDocumentToPage($options = array()) {
		return TRUE;
    }
    
    public function addDocumentToPage($options = array()) {
		$fields = array('dp_document', 'dp_page');
		if (!_required(array('dp_document', 'dp_page'),
		               $options)) {
			return FALSE;
		}
		foreach ($fields as $field) {
			if (isset($options[$field]))
				$this->db->set($field, $options[$field]);
		}	
		$this->db->insert('acs_documents_pages');
		return $this->db->insert_id();
    }
    
    public function deleteDocumentFromPage($options = array()) {
		return TRUE;    	
    }
}
